<?php

namespace App\Http\Controllers\Web\Login;

use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Format\FormatBase;
use App\Mail\MailTest;
use App\Models\CityChinaModel;
use App\Models\OrderModel;
use App\Models\PayConfigModel;
use App\Models\SysMessageModel;
use App\Models\SysUserModel;
use App\Models\SysUserRoleModel;
use App\Models\UserAreaLogsModel;
use App\Models\UserModel;
use App\Models\UserMsmLogsModel;
use App\Models\UserPublicModel;
use App\Models\UserPublicSearchModel;
use App\Models\UserTokenModel;
use App\Services\CurlBasiceService;
use App\Services\Web\UserService;
use App\Tools\AliyunSmsTool;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class UserController extends ApiBaseController
{

    /**
     * 账号密码登录，存session
     * @param Request $request
     * @return object|null
     * @throws Exception
     */
    public function auth_code(Request $request):object
    {
        $params = $request->only(['account', 'password']);

        //验证
        $sysUserOne  = SysUserModel::getUserOne([
            'mobile'=> $params['account'],
            'password'=> md5($params['password']),
        ]);

        if(empty($sysUserOne)){
            //验证
            $sysUserOne  = SysUserModel::getUserOne([
                'account'=> $params['account'],
                'password'=> md5($params['password']),
            ]);
        }

        //成功，返回用户信息，角色，菜单权限
        if (empty($sysUserOne)){
            return $this->codeError([], 1020, '账号或者密码错误');

        }

        //查询部门权限
        $roleInfo = SysUserRoleModel::getSing(['uid'=>$sysUserOne['id']]);
        if (empty($roleInfo['role'][0]['style']) || !in_array($roleInfo['role'][0]['style'], [1, 2])){
            return $this->codeError([], 1020, '没有登录后台的权限');

        }

        $systemInit = UserService::getInstance()->getUserInfo($sysUserOne);

        //获取token
        $where[] = ['user_id', $sysUserOne['id']];
        $where[] = ['status', 3];
        $tokenLogs = UserTokenModel::getUserOne($where);

        $token = '';
        if (empty($tokenLogs)){
            //创建token
            $token = md5($sysUserOne['id'] . time());
            UserTokenModel::insertSingle([
                'token' => $token,
                'user_id' => $sysUserOne['id'],
                'status' => 3,
                'created_at' => time(),
                'expired_at' => time() + (86400 * 7),
            ]);
        }else{
            $token = $tokenLogs['token'];
        }

        $systemInit = array_merge($systemInit, ['token'=> $token]);

        //写入session服务
        Session::put(['admin'=> $systemInit]);

        return $this->codeSuccess($systemInit);

    }

    /**
     * 账号密码登录，存session
     * @param Request $request
     * @return object|null
     * @throws Exception
     */
    public function maintain_auth_code(Request $request):object
    {
        $params = $request->only(['account', 'password']);

        //验证
        $sysUserOne  = SysUserModel::getUserOne([
            'mobile'=> $params['account'],
            'password'=> md5($params['password']),
        ]);

        if(empty($sysUserOne)){
            //验证
            $sysUserOne  = SysUserModel::getUserOne([
                'account'=> $params['account'],
                'password'=> md5($params['password']),
            ]);
        }

        //成功，返回用户信息，角色，菜单权限
        if (empty($sysUserOne)){
            return $this->codeError([], 1020, '账号或者密码错误');

        }

        //查询部门权限
        $roleInfo = SysUserRoleModel::getSing(['uid'=>$sysUserOne['id']]);
        if (empty($roleInfo['role'][0]['style']) || !in_array($roleInfo['role'][0]['style'], [1, 3])){
            return $this->codeError([], 1020, '没有权限');

        }

        $systemInit = UserService::getInstance()->getUserInfo($sysUserOne);

        //获取token
        $where[] = ['user_id', $sysUserOne['id']];
        $where[] = ['status', 4];
        $tokenLogs = UserTokenModel::getUserOne($where);

        $token = '';
        if (empty($tokenLogs)){
            //创建token
            $token = md5($sysUserOne['id'] . time());
            UserTokenModel::insertSingle([
                'token' => $token,
                'user_id' => $sysUserOne['id'],
                'status' => 4,
                'created_at' => time(),
                'expired_at' => time() + (86400 * 7),
            ]);
        }else{
            $token = $tokenLogs['token'];
        }

        $systemInit = array_merge($systemInit, ['token'=> $token]);

        //写入session服务
        Session::put(['admin'=> $systemInit]);

        return $this->codeSuccess($systemInit);

    }

    /**
     * 登出
     * @Author niuyongqiang@kungeek.com
     * @Date 2022/3/21 14:00
     */
    public function logout(Request $request):object
    {
        $params = $request->header('token');

        request()->session()->invalidate();

        //删除token
        UserTokenModel::deleteOne(['token' => $params ?? -1]);

        return $this->codeSuccess();

    }

    /**
     * 个人中心-展示
     * @return object
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function homepage(): object
    {
        $uid = adminInfo('id');

        //获取用户信息
        $userOne = SysUserModel::getOneById($uid, 'id, nickname, sex, mobile, email, account');

        //获取用户角色
        $roleAll = SysUserRoleModel::userRoleAll(['info_sys_user_has_roles.uid'=> $userOne]);
        $roleAll = array_column($roleAll, 'role_id');
        $userOne['role_ids'] = $roleAll[0] ?? 0;

        return $this->codeSuccess($userOne);

    }

    /**
     * 个人中心-修改
     * @param Request $request
     * @return object
     */
    public function homepage_update(Request $request): object
    {
        $params = $request->only(['id','sex','mobile','email','nickname','account','role_id', 'password']);

        if (empty($params['id'])){
            return $this->codeError([], 1022, '参数错误');

        }

        //数据库操作
        $result = UserService::getInstance()->homepageUpdate($params);

        if (!empty($result)){
            return $this->codeError([], $result[0], $result[1]);

        }

        return $this->codeSuccess();

    }

    /**
     * 角色列表
     * @param Request $request
     * @return Object|null
     */
    public function role_data(Request $request): ?Object
    {
        $params = $request->all();

        $result = UserService::getInstance()->roleAll($params);

        //获取数据  权限架构
        return $this->codeSuccess($result);
    }

    /**
     * 添加/修改
     * @param Request $request
     * @return Object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function role_update(Request $request): ?Object
    {
        $data = $request->only('id','role_name','parent_id','description','role_level','status','permission_id','style');

        //用户管理添加/修改
        $res = UserService::getInstance()->roleUpdate($data);
        return $this->codeSuccess([], $res[0], $res[1]);
    }

    /**
     * 删除
     * @param Request $request
     * @return Object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function role_delete(Request $request): ?Object
    {
        $param = $request->only(['id']);

        if (empty($param['id'])){
            return $this->codeError([], 1024, '参数错误');

        }

        //用户管理添加/修改
        $delete['deleted_at'] = time();
        $res = UserService::getInstance()->roleDelete($param['id'], $delete);
        return $this->codeSuccess([], $res[0], $res[1]);
    }

    /**
     * 获取架构信息
     * @param Request $request
     * @return array|null
     */
    public function permission_data(Request $request): ?object
    {
        //获取数据
        $permissionsArr = UserService::getInstance()->whole($request->all());
        //权限架构
        $list = UserService::getInstance()->getPermissionsListByPermissionsIdsLevel($permissionsArr);

        return $this->codeSuccess($list);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return Object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function user_data(Request $request): ?Object
    {
        $params = $request->all();

        $result = UserService::getInstance()->userAll($params);

        //获取数据  权限架构
        return $this->codeSuccess($result);
    }

    /**
     * 添加/修改
     * @param Request $request
     * @return object|null
     */
    public function user_update(Request $request): ?object
    {
        $params = $request->only(['id','mobile','nickname','account','role_id', 'password', 'job_num', 'desc', 'area_province_id', 'area_city_id', 'area_district_id'
            , 'wx_num', 'wx_qcode']);

        $result = UserService::getInstance()->homepageUpdateWhole($params);

        if (!empty($result)){
            return $this->codeError([], $result[0], $result[1]);

        }

        return $this->codeSuccess();
    }


    /**
     * 用户删除
     * @param Request $request
     * @return object|null
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function user_delete(Request $request): ?object
    {
        $param = $request->only(['id']);
        $rules = [
            'id' => 'required|array',
        ];
        $messages = [
            'required' => ':attribute 参数不能为空',
        ];
        $validator = Validator::make($param, $rules, $messages);
        if ($validator->fails()) {
            return $this->codeError([], 1029, $validator->errors()->first());
        }
        //用户管理添加/修改
        $delete['deleted_at'] = time();
        $res = UserService::getInstance()->userDelete($param['id'], $delete);
        return $this->codeSuccess([], $res[0], $res[1]);
    }

    /**
     * 地址列表
     * @param Request $request
     * @return object|null
     */
    public function get_city_china(Request $request): ?object
    {
        $params = $request->only(['parent_code', 'is_tree']);
        $params['is_tree'] = $params['is_tree'] ?? 2;
        if ($params['is_tree'] == 1){
            $res = CityChinaModel::getData([], '', [], 'code, parent_code, name');
            $res = makeTree($res, 'code', 'parent_code');

        }else{
            $res = CityChinaModel::getData(['parent_code' => $params['parent_code'] ?? 0], '', [], 'code, name');

        }

        return $this->codeSuccess($res);
    }

    /**
     * 微信用户列表
     * @param Request $request
     * @return object|null
     */
    public function wechat_user_list(Request $request): ?object
    {
        $params = $request->only(['number', 'id', 'nickname', 'status', 'style', 'limit', 'page', 'mobile', 'area_province_id', 'area_city_id', 'area_district_id']);

        $where = UserService::getInstance()->handleUserStatic($params);

        $list = UserModel::getPage($where, $params['limit'] ?? 15);

        foreach ($list['data'] as &$value){
            // todo 消费记录

            //发布信息
            if (!empty($value['public_data'])){
                $value['public_count'] = count($value['public_data']);
            }else{
                $value['public_count'] = 0;
            }

            //注册时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //信息完善
            if (!empty($value['number'])){
                $value['style_msg'] = 1;

            }else{
                $value['style_msg'] = 2;

            }

            $value['public_pay_num'] = 0;
            $value['public_pay_money'] = 0;
            $value['public_num'] = 0;
            $value['public_money'] = 0;

            //信息统计
            if (!empty($value['public_data'])){
                foreach ($value['public_data'] as $vs){
                    if (!empty($value['public_msg'][$vs['pay_num']]) || !empty($value['public_msg'][$vs['cheer_money']])){
                        $value['public_pay_num'] ++;
                        $value['public_pay_money'] += $value['public_msg'][$vs['pay_num']];
                        $value['public_pay_money'] += $value['public_msg'][$vs['cheer_money']];

                    }else{
                        $value['public_num'] ++;

                    }
                }
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }


            $value['public_num_sum'] = $value['public_pay_num'] + $value['public_num'];

            unset($value['public_data'], $value['area_msg'], $value['city_msg'], $value['address_msg']);
        }

        return $this->codeSuccess(FormatBase::listData($list));

    }

    /**
     * 填充用户信息
     * @param Request $request
     * @return object|null
     */
    public function  add_user_msg(Request $request):?object
    {
        $params = $request->only(['mobile', 'number', 'id', 'name', 'sex', 'birthday', 'job_name', 'area_province_id', 'area_city_id', 'area_district_id'
            , 'status', 'order_time', 'forbid_msg']);

        if (empty($params['id'])){
            return $this->codeError([], 1024, '参数错误');
        }

        $userOne = UserModel::getSingle(['id' => $params['id']]);
        if (empty($userOne)){
            return $this->codeError([], 1024, '用户不存在');
        }


        $data = [];
        if (!empty($params['mobile'])){
            $data['mobile'] = $params['mobile'];

        }

        if (!empty($params['number'])){
            $data['number'] = $params['number'];

        }

        if (!empty($params['name'])){
            $data['name'] = $params['name'];

        }

        if (!empty($params['sex'])){
            $data['sex'] = $params['sex'];

        }

        if (!empty($params['birthday'])){
            $data['birthday'] = $params['birthday'];

        }

        if (!empty($params['job_name'])){
            $data['job_name'] = $params['job_name'];

        }

        if (!empty($params['area_province_id'])){
            $data['area_province_id'] = $params['area_province_id'];

        }

        if (!empty($params['area_city_id'])){
            $data['area_city_id'] = $params['area_city_id'];

        }
        if (!empty($params['area_district_id'])){
            $data['area_district_id'] = $params['area_district_id'];

        }

        if (!empty($params['status'])){
            $data['status'] = $params['status'];

        }

        if (!empty($params['order_time'])){
            $data['order_time'] = time();

        }

        if (!empty($params['forbid_msg'])){
            $data['forbid_msg'] = $params['forbid_msg'];

        }

        if(empty($data)){
            return $this->codeError([], 1024, '内容无修改');

        }


        UserModel::updateSingle(['id' => $params['id']], $data);

        return $this->codeSuccess();
    }

    /**
     * 手机发送短信
     */
    public function maintain_send_sms(Request $request):?object
    {
        $params = $request->only(['mobile']);
        if (empty($params['mobile'])){
            return $this->codeError([], 1024, '参数错误');
        }

        //查询今天发送次数
        $all = UserMsmLogsModel::getUserData([
            ['phone', '=', $params['mobile']],
            ['created_at', '>=', strtotime(date('Y-m-d', time()))]
        ]);

        if (count($all) >= 5){
            return $this->codeError([], 1024, '今日获取验证码次数已达上限，请明日再来');
        }

        $rand = rand(10000, 99999);
        //发送短信
        $result = AliyunSmsTool::main($params['mobile'], $rand);

        if (!$result){
            return $this->codeError([], 1011, '短信发送失败');
        }

        //发送成功入库
        UserMsmLogsModel::insertSingle([
            'code'=> $rand,
            'phone'=> $params['mobile'],
            'created_at'=> time(),
        ]);

        return $this->codeSuccess();
    }

    /**
     * 验证验证码，后修改密码
     */
    public function maintain_update_password(Request $request):?object
    {
        $params = $request->only(['mobile', 'sms_code', 'password']);

        //发送成功入库
        $userSms = UserMsmLogsModel::getSingle([
                ['phone', '=', $params['mobile']],
                [ 'created_at', '>', time() - 300]
            ]
        );

        if (empty($userSms)){
            return $this->codeError([], 1019, '验证码校验失败');

        }

        if ($userSms['code'] <> $params['sms_code']){
            //验证不通过
            return $this->codeError([], 1019, '验证码校验失败');

        }

        //成功，写入用户表
        SysUserModel::updateSingle(['mobile'=> $params['mobile']], ['password'=> md5($params['password'])]);

        return $this->codeSuccess();
    }

    public function upload(Request $request):?object
    {
        //获取图片的扩展名
        $file = $request->file('file');
        $extension = $file->getClientOriginalExtension();

        $name = $extension;

        //定义新的文件名
        $name_pix = time() . rand(1000,9999);
        $filename= 'oss_img/' . date('Y-m-d').'/' . $name_pix;
        // public_path 是以 public 文件夹为根目录
        $isPath = public_path('oss_img/');
        // 1、先检查文件夹是否存在；2、不存在则新建文件夹
        File::isDirectory($isPath) or File::makeDirectory($isPath, 0777, true, true);

        $r = Storage::disk()->put($filename,$file);

        return $this->codeSuccess([
            'file'=> 'storage/' . $r
        ]);

    }

    public function callback_order()
    {
        $res = file_get_contents("php://input");

        writeLoToFile("notify_url_api", '支付订单回调0：', json_encode($res));

        $res = simplexml_load_string($res,'SimpleXMLElement', LIBXML_NOCDATA);
        if (!empty($res)){
            $res = (array)$res;
        }

        writeLoToFile("notify_url_api", '支付订单回调1：', json_encode($res));

        // 判断签名是否正确  判断支付状态
        if (!empty($res) && ($res['result_code'] == 'SUCCESS')) {
            //获取服务器返回的数据
            $order_sn = $res['out_trade_no'];          // 订单单号
            $openid = $res['openid'];                  // 付款人openID
            $total_fee = ($res['total_fee']) / 100;            // 付款金额
            $transaction_id = $res['transaction_id'];  // 微信支付流水号

            //查找订单
            $order = OrderModel::getSingle([
                'id' => $order_sn,
            ]);
            writeLoToFile("notify_url_api", '支付订单回调2.1：', json_encode($order ?? ''));

            if ($order) {   // 订单是否存在
                DB::beginTransaction();
                try {
                    // 更新订单状态(order)
                    OrderModel::updateSingle(['id' => $order_sn], ['status' => 1]);
                    writeLoToFile("notify_url_api", '支付订单回调3：', json_encode($order_sn ?? ''));

                    if (in_array($order['style'], [1,2,3,5,6])) {
                        //修改任务状态
                        $temp_pay = PayConfigModel::getUserData();
                        $temp_money_message = '编辑、发布、引流';

                        if (!empty($temp_pay)){
                            foreach ($temp_pay as $tvs){
                                if($order['money'] == $tvs['num']){
                                    $temp_money_message = $tvs['msg'];
                                }
                            }
                        }

                        UserPublicModel::updateSingle(['id' => $order['public_id']], ['status' => 1, 'is_pay'=> 1, 'money_message'=> $temp_money_message, 'handle_time'=> time()]);
                    }else if($order['style'] == 7){
                        //搜索发布
                        UserPublicSearchModel::updateSingle(['id' => $order['public_id']], ['status' => 1, 'is_pay'=> 1, 'handle_time'=> time()]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    $res = false;

                    writeLoToFile("notify_url_api", '失败回调：', json_encode($e ?? ''));

                    Db::rollback();
                }

            } else {
                writeLoToFile("notify_url_api", '支付订单回调10：', json_encode($result ?? ''));

                // 订单不存在
                $res = false;
            }
        } else {
            writeLoToFile("notify_url_api", '支付订单回调11：', json_encode($result ?? ''));

            $res = false;
        }

        writeLoToFile("notify_url_api", '支付订单回调12：', '结束');


        // 返回状态给微信服务器
        if (!empty($res)) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }

        echo $str;
    }

//    public function dingding(Request $request){
//        $params = $request->all();
//        $res = file_get_contents("php://input");
//        $params_json = json_decode($res, true);
//        writeLoToFile("dingding", '钉钉回调0：', $res);
//        writeLoToFile("dingding", '钉钉回调1：', json_encode($params, 256));
//
//        require_once app_path('Tools/taobao_sdk_PHP/TopSdk.php');
//
//        date_default_timezone_set('Asia/Shanghai');
//
//        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
//        $req = new \OapiServiceGetAuthInfoRequest;
////        $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/service/get_auth_info");
//
//
//    }

    public function dingding(Request $request)
    {
        $params = $request->all();

        require_once app_path('Services/Web/DingCallbackCrypto.php');

        $res = file_get_contents("php://input");

        $params_json = json_decode($res, true);
        writeLoToFile("dingding", '钉钉回调0：', $res);
        writeLoToFile("dingding", '钉钉回调1：', json_encode($params, 256));

        $token = '5nGK761yliKTNLIsgwWIabeCf';
        $aesKey = 'EkheiVfLUmCKvKhequsHpFjv26Z0E8CFtuEwJZWWsol';
        $ownerKey = 'dingcsy5rkgaol8awo9g';

        $dingCallbackCrypto = new \DingCallbackCrypto($token, $aesKey, $ownerKey);

        $signature = $dingCallbackCrypto->getDecryptMsg($params['signature'], $params['timestamp'], $params['nonce'], $params_json['encrypt']);
        writeLoToFile("dingding", '钉钉回调2：', json_encode($signature, 256));


        $timeStamp = $params['timestamp'];
        $nonce = $params['nonce'];
        return $dingCallbackCrypto->getEncryptedMap("success");
    }

    public function oa_topic(Request $request): object
    {
        $params = $request->all();
        $result1 = CurlBasiceService::httpPost('https://oapi.dingtalk.com/topapi/v2/user/get?access_token=af2dede5cbb93102880ceae44d712a0f'
            , json_encode(['userid'=> 'manager4195']), '');

        $result2 = [];
        if(!empty($result1['result']['dept_id_list'])){
            $result2 = CurlBasiceService::httpPost('https://oapi.dingtalk.com/topapi/v2/department/get?access_token=af2dede5cbb93102880ceae44d712a0f'
                , json_encode(['dept_id'=> $result1['result']['dept_id_list'][0]]), '');
        }

        return $this->codeSuccess([
            'result1'=> $result1,
            'dept_id_list'=> $result1['result']['dept_id_list'],
            'result2'=> $result2,
        ]);
    }

    public function oa_model_topic(Request $request): object
    {
        $params = $request->all();
        $result1 = CurlBasiceService::httpGet('https://api.dingtalk.com/v1.0/workflow/processInstances?processInstanceId=V-LnR5d-Q8WH6MdDAL1a8A01811710310967'
        , [
                'x-acs-dingtalk-access-token: b520895dd6ca315893d4695aafec884d'
            ]);

        return $this->codeSuccess(json_decode($result1, true));
    }

    public function oa_access_token(Request $request): object
    {
        $params = $request->all();
        $result1 = CurlBasiceService::httpPost('https://api.dingtalk.com/v1.0/oauth2/accessToken'
            , json_encode([
                'appKey' => 'dingcsy5rkgaol8awo9g',
                'appSecret' => 'VVC6DmUU-suGFVH9gzhF4DmXkfl9U7J2J4iZ_IqBzR7InVkBL_LHYmhFYjK2AVWK',
            ]), '');

        return $this->codeSuccess($result1);

    }

    public function click_user_task(Request $request): object
    {
        $params = $request->only(['user_id']);
        if (empty($params['user_id'])){
            return $this->codeError([], 1001, '参数错误');
        }

        UserModel::updateSingle(['id'=> $params['user_id']], [
            'order_time'=> time(),
        ]);
        return $this->codeSuccess();
    }

}
